package cn.itcast.bos.service.transit.impl;

import cn.itcast.bos.dao.take_delivery.WayBillRepository;
import cn.itcast.bos.dao.transit.TransitInfoRepository;
import cn.itcast.bos.domain.take_delivery.WayBill;
import cn.itcast.bos.domain.transit.TransitInfo;
import cn.itcast.bos.index.WayBillIndexRepository;
import cn.itcast.bos.service.transit.TransitInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class TransitInfoServiceImpl implements TransitInfoService {

    @Autowired
    private TransitInfoRepository transitInfoRepository;
    @Autowired
    private WayBillRepository wayBillRepository;
    @Autowired
    private WayBillIndexRepository wayBillIndexRepository;

    @Override
    public void create(String wayBillIds) {
        String[] wayBillIdArray = wayBillIds.split(",");
        if (StringUtils.isNoneBlank(wayBillIdArray)) {
            for (String wayBillId : wayBillIdArray) {
                WayBill wayBill = wayBillRepository.findOne(Integer.parseInt(wayBillId));
                if (wayBill.getSignStatus() == 1) {
                    TransitInfo transitInfo = new TransitInfo();
                    transitInfo.setWayBill(wayBill);
                    transitInfo.setStatus("出入库中转");
                    wayBill.setSignStatus(2);
                    wayBillRepository.save(wayBill);
                    wayBillIndexRepository.save(wayBill);
                    transitInfoRepository.save(transitInfo);
                } else {
                    throw new RuntimeException("运单已经处于配送状态");
                }
            }
        }
    }

    @Override
    public Page<TransitInfo> findAll(Pageable pageable) {
        return transitInfoRepository.findAll(pageable);
    }
}
